package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.repository.DatabaseUserRepository;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.service.impl.UserServiceImpl;
import org.geektimes.projects.user.sql.DBConnectionManager;
import org.geektimes.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.sql.SQLException;

@Path("/user")
public class UserRegisterController implements PageController {

    private UserService userService;

    public UserRegisterController() {
        try {
            this.userService =new UserServiceImpl(new DatabaseUserRepository(DBConnectionManager.getConnection()));
        } catch (SQLException | ClassNotFoundException throwable) {
            throwable.printStackTrace();
        }
    }

    @Path("/registerUser")
    @POST
    public String execute(HttpServletRequest request, HttpServletResponse res){
        try {
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String phoneNumber = request.getParameter("phoneNumber");
            User user = new User();
            user.setName(name);
            user.setPassword(password);
            user.setEmail(email);
            user.setPhoneNumber(phoneNumber);
            userService.register(user);
            return "success.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error",e.getMessage());
            return "error.jsp";
        }
    }
}
